import Vue from 'vue'
import vueRouter from 'vue-router'
import ElementUI from 'element-ui'

Vue.use(vueRouter)
Vue.use(ElementUI)

import Login from './pages/login.vue'
import Home from './pages/home.vue'
import Register from './pages/register.vue'
import config from './config'

var router = new vueRouter({
    routes: [
        { path: '/', redirect: '/home' },
        { path: '/login', component: Login, name: 'login' },
        { path: '/home', component: Home, name: 'home' },
        { path: '/register', component: Register, name: 'register' },
    ]
})

// Vue实例在router对象的router.app内
router.beforeEach(async (to, from, next) => {
    
    if(to.name === 'login' || to.name === 'register') {
        next()
    }
    else {
        let token = localStorage.getItem('token')
        let res = await router.app.$http.post(config.baseURL+'users/jwtcheck', {token: token})
        if(token && res.data.code === 0) {
            next()
        }
        else {
            ElementUI.Message({
                showClose: true,
                message: '您还未登录！',
                type: 'warning'
            })
            next({name: 'login'})
        }
    }

})

export default router